
% load(fullfile(LFW.dbpath, 'ImgPairs.mat'))
% load(fullfile(LFW.dbpath, 'FeaturePairs.mat'))
% load(fullfile(LFW.dbpath, 'VGGFeaturePairs.mat'))

PairNum = size(Features1, 2);
HalfNum = PairNum / 2;

n_fold = 10;
n_num = 300;
svmcmd = '-t 0 -h 0';
same_label = [ones(HalfNum, 1); zeros(HalfNum, 1)];
accuracies = zeros(n_fold, 1);

%%
% F1 = Features1';
% % F1 = (F11>0);
% % F1 = sign(F1) .* sqrt(abs(F1));
% % F1 = bsxfun(@minus,F1,PCAmap.mean);
% % F1 = F1 * PCAmap.M;
% 
% F2 = Features2';
% % F2 = (F21>0);
% % F2 = sign(F1) .* sqrt(abs(F2));
% % F2 = bsxfun(@minus,F2,PCAmap.mean);
% % F2 = F2 * PCAmap.M;
% 
% % F1 = Features1';
% % F2 = Features2';

F1 = normdic(Features1)';
F2 = normdic(Features2)';

% scores = zeros(PairNum, 1);
% for i = 1 : PairNum
% %     scores(i) = F1(i,:) * mapping.A * F1(i,:)' + F2(i,:) * mapping.A * F2(i,:)' - 2 * F1(i,:) * mapping.G * F2(i,:)';
%     scores(i) = pdist2(F1(i,:), F2(i,:));
% %     scores(i) = F1(i,:) * F2(i,:)';
% end

% scores = sqrt(sum((F1 - F2).^2, 2));
% scores = sqrt(sum(F1 .* F2, 2));
scores = sum(F1 .* F2, 2);

%%
figure;
hist(scores(1 : PairNum/2), 500); hold on
hist(scores(PairNum/2+1 : end), 500);

%% output
pp1 = 0; pp2 = HalfNum;
for i = 1 : n_fold
    pp1 = pp1(end)+1 : pp1(end)+n_num;
    pp2 = pp2(end)+1 : pp2(end)+n_num;
    pp = [pp1 pp2];
    train_idx = 1 : PairNum;
    train_idx(pp) = [];
    
    model = libsvm.svmtrain(same_label(train_idx), scores(train_idx), svmcmd);
    
    [class, accuracy, deci] = libsvm.svmpredict(same_label(pp), scores(pp), model);
    accuracies(i) = accuracy(1);
    fprintf('fold = %d/%d, accuracy = %.2f%%\n', i, n_fold, accuracies(i));
end

%%
model = libsvm.svmtrain(same_label, scores, svmcmd);
[class, accuracy, deci] = libsvm.svmpredict(same_label, scores, model);
% mean(scores(same_label==1)) / 4 + mean(max(0,1 - scores(same_label==0))) / 4
% sum((scores<0.22) == same_label) / 6000

%%
mu = mean(accuracies);
fprintf('\nmean accuracy = %.2f%%\n\n', mu);
